﻿using System;
using System.Collections.Generic;
using System.Collections;
using System.Linq;
using System.Text;
using FCNS.Data.Table;
using System.Windows.Controls;
using System.Windows.Documents;
using System.IO;
using Table = FCNS.Data.Table;
using System.Windows.Data;
using DoubleH.Utility.Configuration;
using FCNS.Data;

namespace DoubleH.Utility
{
    public class PrintFunction
    {
        static DoubleH.Utility.Configuration.PrintConfig config = null;
        static object corSId = null;
        public delegate bool PrintOrder(object order, DataTableText tableText);
        public static event PrintOrder BeginPrintOrder;

        public static void PrintPosOrder(Table.PosOrderS order)
        {
            string file = DbDefine.printDir + "pos.html";
            if (!File.Exists(file))
            {
                MessageWindow.Show("打印模板丢失");
                return;
            }
            StringBuilder sb = new StringBuilder(File.ReadAllText(file, UTF8Encoding.UTF8));
            ReplaceText(sb, order);

            System.Windows.Forms.WebBrowser web = new System.Windows.Forms.WebBrowser();
            web.DocumentText = sb.ToString();//如果打印的内容不齐全,就使用事件处理
            web.DocumentCompleted += new System.Windows.Forms.WebBrowserDocumentCompletedEventHandler(web_DocumentCompleted);
        }

        public static void PrintPosJiaoBan(string user, string pos, string getMoney, string allMoney)
        {
            string file = DbDefine.printDir+ "posOver.html";
            if (!File.Exists(file))
            {
                MessageWindow.Show("打印模板丢失");
                return;
            }
            StringBuilder sb = new StringBuilder(File.ReadAllText(file, UTF8Encoding.UTF8));
            sb.Replace("[user]", user);
            sb.Replace("[pos]", pos);
            sb.Replace("[getMoney]", getMoney);
            sb.Replace("[allMoney]", allMoney);
            sb.Replace("[dateTime]", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));

            System.Windows.Forms.WebBrowser web = new System.Windows.Forms.WebBrowser();
            web.DocumentText = sb.ToString();//如果打印的内容不齐全,就使用事件处理
            web.DocumentCompleted += new System.Windows.Forms.WebBrowserDocumentCompletedEventHandler(web_DocumentCompleted);
        }

        static void web_DocumentCompleted(object sender, System.Windows.Forms.WebBrowserDocumentCompletedEventArgs e)
        {
            System.Windows.Forms.WebBrowser web = sender as System.Windows.Forms.WebBrowser;
            web.Print();
            AppDebug(web.DocumentText);
            web.Dispose();
            web = null;
        }


        public static void Print(object order, DataTableText tableText)
        {
            if (order == null)
                return;

            if (BeginPrintOrder != null)//一定要验证这个啊
                if (!BeginPrintOrder(order, tableText))
                    return;

            string file = string.Empty;
            config = DoubleHConfig.AppConfig.PrintConfigItems.Find(f => f.TableText == tableText.ToString());
            if (config == null)
            {
                DoubleHConfig.AppConfig.PrintConfigItems.Add(config = new Configuration.PrintConfig() { TableText = tableText.ToString() });
                string[] str = order.GetType().ToString().Split('.');
                if (str.Length != 0)
                    file = DbDefine.printDir + str[str.Length - 1] + ".html";
            }
            else
                file = DbDefine.printDir + config.FileName;

            if (!ExistsFile(file))
                return;

            StringBuilder sb = new StringBuilder(File.ReadAllText(file, UTF8Encoding.UTF8));
            ReplaceText(sb, order);
            AppDebug(sb.ToString());
            ShowPrint(sb.ToString());
        }

        public static void PrintList(DataGrid dataGridObject, DataTableText tableText)
        {
            if (dataGridObject == null || !dataGridObject.HasItems)
                return;

            string file = string.Empty;
            config = DoubleHConfig.AppConfig.PrintConfigItems.Find(f => f.TableText == tableText.ToString());
            if (config == null)
            {
                DoubleHConfig.AppConfig.PrintConfigItems.Add(config = new Configuration.PrintConfig() { TableText = tableText.ToString() });
                file = DbDefine.printDir + "List.html";
            }
            else
                file = DbDefine.printDir + config.FileName;

            if (!ExistsFile(file))
                return;

            StringBuilder sb = new StringBuilder(File.ReadAllText(file, UTF8Encoding.UTF8));
            StringBuilder sb2 = new StringBuilder("<table class='detailClass' width='100%' border='0'><tr>");
            for (int j = 0; j < dataGridObject.Columns.Count; j++)
                sb2.Append("<td class='detailTd" + j + "'>" + dataGridObject.Columns[j].Header + "</td>");

            sb2.Append("</tr>");
            //内容
            for (int i = 0; i < dataGridObject.Items.Count; i++)
            {
                var vr = dataGridObject.Items[i];
                Type ty = vr.GetType();
                sb2.Append("<tr>");
                for (int j = 0; j < dataGridObject.Columns.Count; j++)
                {
                    DataGridTextColumn gvc = (DataGridTextColumn)dataGridObject.Columns[j];
                    string bingPath = ((Binding)gvc.Binding).Path.Path;
                    System.Reflection.PropertyInfo vt = ty.GetProperty(bingPath);
                    try
                    {
                        object obj = vt.GetValue(vr, null);
                        sb2.Append("<td class='detailTd_" + bingPath + "'>" + (obj == null ? string.Empty : obj.ToString()) + "</td>");
                    }
                    catch { sb2.Append("<td class='detailTd_" + bingPath + "'></td>"); }
                }
                sb2.Append("</tr>");
            }
            sb2.Append("</table>");
            sb.Replace("[objList]", sb2.ToString());
            sb.Replace("[CompanyName]", SysConfig.SysConfigParams.CompanyName);
            sb.Replace("[CompanyTel]", SysConfig.SysConfigParams.CompanyTel);
            sb.Replace("[CompanyAddress]", SysConfig.SysConfigParams.CompanyAddress);

            AppDebug(sb.ToString());
            ShowPrint(sb.ToString());
        }

        private static void ShowPrint(string html)
        {
            FormPrint fp = new FormPrint();
            fp.Init(corSId, config);
            fp.webBrowser1.DocumentText = html;
            fp.Show();
        }

        private static bool ExistsFile(string fileName)
        {
            if (!File.Exists(fileName))
            {
                MessageWindow.Show(fileName + "打印格式丢失");
                PrintConfig cf = new PrintConfig();
                cf.Init(config);
                cf.ShowDialog();
                return false;
            }
            return true;
        }
        //替换网页文本,只能替换固定的字段值
        private static void ReplaceText(StringBuilder sb, object order)
        {
            Type ty = order.GetType();
            System.Reflection.PropertyInfo pi = ty.GetProperty("CorSId");
            if (pi != null)
                corSId = pi.GetValue(order, null);

            foreach (System.Reflection.PropertyInfo info in ty.GetProperties())
            {
                object obj = info.GetValue(order, null) ?? "";
                sb.Replace("[" + info.Name + "]", obj.ToString());

                switch (info.Name)
                {
                    case "ProductSList":
                        //设置列表型的数据 [objList] 为网页中的定点标记
                        IList<Table.ProductS> ps = (IList<Table.ProductS>)obj;
                        sb.Replace("[objList]", SetList(ps));
                        break;

                    case "ProductInRepairSList":
                        IList<Table.ProductSInRepairS> pirs = (IList<Table.ProductSInRepairS>)obj;
                        sb.Replace("[objList]", SetList(pirs));
                        break;

                    case "ProductInWeiBaoSList":
                        IList<Table.ProductSInWeiBaoS> pibs = (IList<Table.ProductSInWeiBaoS>)obj;
                        sb.Replace("[objList]", SetList(pibs));
                        break;
                }
            }

            sb.Replace("[CompanyName]", SysConfig.SysConfigParams.CompanyName);
            sb.Replace("[CompanyTel]", SysConfig.SysConfigParams.CompanyTel);
            sb.Replace("[CompanyAddress]", SysConfig.SysConfigParams.CompanyAddress);
        }

        private static string SetList(IList<Table.ProductS> productS)
        {
            Type ty = typeof(Table.ProductS);
            StringBuilder sb = new StringBuilder("var objList=new Array();");
            for (int i = 0; i < productS.Count; i++)
            {
                string key = "i" + i;
                sb.Append("var " + key + "=new Array();");
                Table.ProductS ps = productS[i];
                foreach (System.Reflection.PropertyInfo info in ty.GetProperties())
                {
                    object obj = info.GetValue(ps, null) ?? "";
                    sb.Append(key + "[\"" + info.Name + "\"]=\"" + obj.ToString() + "\";");
                }
                sb.Append("objList[" + i + "]=" + key + ";");
            }
            if (config != null)
            {
                int count = productS.Count;
                while (count < config.Row)
                {
                    string key = "i" + count;
                    sb.Append("var " + key + "=new Array();");
                    sb.Append("objList[" + count + "]=" + key + ";");
                    count += 1;
                }
            }
            return sb.ToString();
        }
        private static string SetList(IList<Table.ProductSInRepairS> productS)
        {
            Type ty = typeof(Table.ProductS);
            StringBuilder sb = new StringBuilder("var objList=new Array();");
            for (int i = 0; i < productS.Count; i++)
            {
                string key = "i" + i;
                sb.Append("var " + key + "=new Array();");
                Table.ProductSInRepairS ps = productS[i];
                foreach (System.Reflection.PropertyInfo info in ty.GetProperties())
                {
                    if (ps.Id == -1)
                        sb.Append(key + "[\"" + info.Name + "\"]=\"\";");
                    else
                    {
                        object obj = info.GetValue(ps, null) ?? "";
                        sb.Append(key + "[\"" + info.Name + "\"]=\"" + obj.ToString() + "\";");
                    }
                }
                sb.Append("objList[" + i + "]=" + key + ";");
            }
            return sb.ToString();
        }
        private static string SetList(IList<Table.ProductSInWeiBaoS> productS)
        {
            Type ty = typeof(Table.ProductS);
            StringBuilder sb = new StringBuilder("var objList=new Array();");
            for (int i = 0; i < productS.Count; i++)
            {
                string key = "i" + i;
                sb.Append("var " + key + "=new Array();");
                Table.ProductSInWeiBaoS ps = productS[i];
                foreach (System.Reflection.PropertyInfo info in ty.GetProperties())
                {
                    if (ps.Id == -1)
                        sb.Append(key + "[\"" + info.Name + "\"]=\"\";");
                    else
                    {
                        object obj = info.GetValue(ps, null) ?? "";
                        sb.Append(key + "[\"" + info.Name + "\"]=\"" + obj.ToString() + "\";");
                    }
                }
                sb.Append("objList[" + i + "]=" + key + ";");
            }
            return sb.ToString();
        }


        private static void AppDebug(string html)
        {
            if (DoubleHConfig.AppConfig.AppDebug)
                File.WriteAllText("print.html", html);
        }

    }
}